package cn.favebook.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.dbutils.QueryRunner;

import java.util.HashMap;
import java.util.Map;

import cn.favebook.Global;
import cn.favebook.bean.User;
import cn.favebook.db.UserDao;

/**
 * Servlet implementation class indexSignServlet
 */
@WebServlet("/SignupServlet")
public class SignupServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String vcode = getContent(request.getPart("vcode"));
		String expected = (String) request.getSession().getAttribute(Global.VCODE_KEY);
		if(!vcode.equals(expected)) {
			response.sendRedirect("signup.jsp");
			return;
		}
		
		Map<String, String> map = new HashMap<>();
		for(Part part : request.getParts()) {
			String key = part.getName();
			String content = getContent(part);
			if (map.get(key) == null) {
				map.put(key, content);
			} else {
				String newValue = map.get(key) + ',' + content;
				map.put(key, newValue);
			}
		}
		QueryRunner runner = (QueryRunner) request.getServletContext().getAttribute("runner");
		User user = new User(map.get("username"), map.get("password"), map.get("eamil"));
		try {
			UserDao.register(runner, user);
		} catch (Exception e) {
			e.printStackTrace();
			response.sendError(500);
			return;
		}
		response.sendRedirect("./signin.jsp");
		
	}
	
	private String getContent(Part part) throws IOException {
		try(Scanner scanner = new Scanner(part.getInputStream())) {
			return scanner.next();
		}
	}

}
